<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form v-loading="loading" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
      label-width="120px">
      <el-tabs type="card" v-model="selectTab">
        <el-tab-pane name="0">
          <span slot="label"><i class="el-icon-date"></i>{{ $t('role.infoTab') }}</span>
          <el-form-item prop="name" :label="$t('role.name')">
            <el-input v-model="dataForm.name" :placeholder="$t('role.name')"></el-input>
          </el-form-item>
          <el-form-item prop="remark" :label="$t('role.remark')">
            <el-input v-model="dataForm.remark" :placeholder="$t('role.remark')"></el-input>
          </el-form-item>
          <el-form-item prop="deptId" :label="$t('role.deptName')" class="dept-list">
            <uni-tree-select v-model="dataForm.deptId" ref="treeSelectDept" :data="deptList" />
          </el-form-item>
          <el-form-item prop="roleGrade" :label="$t('role.roleGrade')" class="role-list" v-if="roleGradesList.length > 1 && dataForm.roleGrade !== '1'">
            <el-select v-model="dataForm.roleGrade" :placeholder="$t('role.roleGrade')">
              <el-option v-for="roleGrade in roleGradesList" :key="roleGrade.key" :label="roleGrade.value" :value="roleGrade.key"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane :label="$t('role.menuTab')" name="1">
          <el-form-item size="mini" :label="$t('role.menuList')">
            <el-tree :data="menuList" :props="{ label: 'name', children: 'children' }" node-key="id" ref="menuListTree"
              accordion show-checkbox>
            </el-tree>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane :label="$t('role.dsTab')" name="2">
          <el-form-item v-for="(item) in this.dataForm.roleRuleList" :key="item.id" :label="item.ruleSortName">
            <el-col :span="10">
              <el-select v-model="item.ruleId" clearable>
                <el-option v-for="item1 in item.ruleDataList" :key="item1.id" :label="item1.name" :value="item1.id">
                </el-option>
              </el-select>
            </el-col>
            <!-- <el-col :span="2">{{ item.customDataText }}</el-col>
            <el-col :span="12">
              <uni-tree-select v-model="item.customDataIds" :selectParams="{ multiple: true}" :treeParams="{ clickParent: true}"
                :data="item.treeData" />
            </el-col> -->
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { treeDataTranslate } from '@/utils/index'
export default {
  data () {
    return {
      selectTab: '0',
      visible: false,
      loading: false,
      deptListVisible: false,
      menuList: [],
      deptList: [],
      roleGradesList: [],
      // roleDataDeptList: [],
      CODE_AUTHSCOPE_DATA_DEPT: 'DS_DEPT',
      dataForm: {
        id: '',
        name: '',
        deptId: '',
        // deptName: '',
        roleGrade: '0',
        menuIdList: [],
        deptIdList: [],
        remark: '',
        roleRuleList: []
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  components: {},
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([])
        Promise.all([
          this.getMenuList(),
          this.getDeptList(),
          this.getRoleGradesList()
          // this.getRoleDataDeptList()
        ]).then(() => {
          this.getInfo()
        })
        this.selectTab = '0'
      })
    },
    // 获取菜单列表
    getMenuList () {
      return this.$http.get('/sys/menu/selectAuth').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.menuList = []
        let clients = this.$getDictList('SYS_MENU_CLIENT', true)
        clients.forEach((client) => {
          let children = res.data.filter((menu) => {
            return menu.client === client.val
          })
          this.menuList.push({
            id: 'client_' + client.val,
            showFlag: 1,
            pid: '-1',
            name: client.label,
            client: client.val,
            icon: 'icon-project',
            menuClass: client.val,
            children: children
          })
        })
      }).catch(() => { })
    },
    // 获取部门列表
    getDeptList () {
      return this.$http.get('/sys/dept/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.deptList = treeDataTranslate(res.data)
      }).catch(() => { })
    },
    // 获取角色级别
    getRoleGradesList () {
      return this.$http.get('/sys/role/roleGrades').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.roleGradesList = res.data
      }).catch(() => { })
    },

    // // 获取数据权限 - 部门规则待选项
    // getRoleDataDeptList () {
    //   return this.$http.get('/sys/sysruledata/list', { params: { ruleSort: this.CODE_AUTHSCOPE_DATA_DEPT } }).then(({ data: res }) => {
    //     if (res.code !== 0) {
    //       return
    //     }
    //     this.roleDataDeptList = res.data
    //   }).catch(() => { })
    // },
    // 获取信息
    getInfo () {
      this.loading = true
      let id = this.dataForm.id || -1
      this.$http.get(`/sys/role/${id}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.dataForm.menuIdList.forEach(item => this.$refs.menuListTree.setChecked(item, true))
      }).catch(() => { })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.dataForm.menuIdList = [
          ...this.$refs.menuListTree.getCheckedKeys(),
          ...this.$refs.menuListTree.getHalfCheckedKeys()
        ]
        this.dataForm.menuIdList = this.dataForm.menuIdList.filter(menuId => {
          return !this.$xeutils.startsWith(menuId, 'client')
        })
        // 设置选定的自定义字符串
        for (let item of this.dataForm.roleRuleList) {
          // item.customData = (item.customDataIds || []).join(',')
          item.customData = ''
        }
        this.loading = true
        this.$http[!this.dataForm.id ? 'post' : 'put']('/sys/role', this.dataForm).then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { })
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>
